/***************************************************************************
 *   Copyright (C) 2008 by BogDan Vatra                                    *
 *   bogdan@licentia.eu                                                    *
 *                                                                         *
 *   This program is free software: you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation, either version 3 of the License, or     *
 *   (at your option) any later version.                                   *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
 ***************************************************************************/

#include <QFile>
#include <QFileDialog>
#include <QSqlQuery>
#include <QMessageBox>
#include <QDebug>

#include "preluareObinvDos.h"
#include <database.h>
#include <query.h>

using namespace SQL;

PreluareObinvDosObiecteInventar::PreluareObinvDosObiecteInventar(QWidget* parent, Qt::WFlags fl)
		: KontAMabilWindow(parent, fl), Ui::preluareObinvDosObiecteInventarForm()
{
	setupUi(this);
	if (m_ObinvDir.exists("c:/OBINV"))
		m_ObinvDir.cd("c:/OBINV");
	m_obinvFound = checkForObinv();
	preiaButton->setEnabled(m_obinvFound);
}

void PreluareObinvDosObiecteInventar::on_locatieObinv_clicked()
{
/*
	QFile file("/tob.csv");
	if (!file.open(QIODevice::Text|QIODevice::ReadOnly))
		return;
	QStringList linie;
	file.readLine();
	int a=0;
	while(!file.atEnd())
	{
		linie=QString(file.readLine()).split("\t");
		a++;
		if (8!=linie.size())
		{
			qDebug()<<a<<linie;
			continue;
		}
		if (!defaultDatabase()->query("gestiuniObiecteInventar")->locate("cod",linie[0].trimmed()))
		{
			defaultDatabase()->query("gestiuniObiecteInventar")->insert();
			defaultDatabase()->query("gestiuniObiecteInventar")->setValue("cod", linie[0].trimmed().toLower());
			defaultDatabase()->query("gestiuniObiecteInventar")->setValue("denumire", linie[0].trimmed());
			defaultDatabase()->query("gestiuniObiecteInventar")->post();
		}

		if (!defaultDatabase()->query("um")->locate("denumire",linie[4].trimmed()))
		{
			defaultDatabase()->query("um")->insert();
			defaultDatabase()->query("um")->setValue("denumire", linie[4].trimmed());
			defaultDatabase()->query("um")->post();
		}

		defaultDatabase()->query("repereObiecteInventar")->bindValue("id_gestiune",defaultDatabase()->query("gestiuniObiecteInventar")->value("id"));
		defaultDatabase()->query("repereObiecteInventar")->select();
		defaultDatabase()->query("repereObiecteInventar")->insert();
		defaultDatabase()->query("repereObiecteInventar")->setValue("denumire",linie[1].trimmed());
		defaultDatabase()->query("repereObiecteInventar")->setValue("id_um",defaultDatabase()->query("um")->value("id"));
		defaultDatabase()->query("repereObiecteInventar")->setValue("cod_cpsa",linie[2].trimmed());
		defaultDatabase()->query("repereObiecteInventar")->setValue("nr_inv",linie[3].trimmed());
		try
		{
			defaultDatabase()->query("repereObiecteInventar")->post();
		}
		catch(...)
		{
			qDebug()<<a<<linie;
			continue;
		}
		QDate data;
		if (linie[7].trimmed().split(".").size()==3)
			data=QDate(linie[7].trimmed().split(".")[2].toInt(), linie[7].trimmed().split(".")[1].toInt(), linie[7].trimmed().split(".")[0].toInt());
		else
			data=QDate(linie[7].trimmed().left(4).toInt(), linie[7].trimmed().mid(4, 2).toInt(), linie[7].trimmed().mid(6, 2).toInt());
		defaultDatabase()->query("acteIntrariObiecteInventar")->bindValue(":data", data);
		defaultDatabase()->query("acteIntrariObiecteInventar")->select();
		if (!defaultDatabase()->query("acteIntrariObiecteInventar")->locate("numar","sold"))
		{
			defaultDatabase()->query("acteIntrariObiecteInventar")->insert();
			defaultDatabase()->query("acteIntrariObiecteInventar")->setValue("numar", "sold");
			defaultDatabase()->query("acteIntrariObiecteInventar")->setValue("data", data);
			defaultDatabase()->query("acteIntrariObiecteInventar")->post();
		}
		defaultDatabase()->query("pozitiiIntrariObiecteInventar")->bindValue("id_act", defaultDatabase()->query("acteIntrariObiecteInventar")->value("id"));
		defaultDatabase()->query("pozitiiIntrariObiecteInventar")->select();
		defaultDatabase()->query("pozitiiIntrariObiecteInventar")->insert();
		defaultDatabase()->query("pozitiiIntrariObiecteInventar")->setValue("data", data);
		defaultDatabase()->query("pozitiiIntrariObiecteInventar")->setValue("id_reper", defaultDatabase()->query("repereObiecteInventar")->value("id"));
		defaultDatabase()->query("pozitiiIntrariObiecteInventar")->setValue("pret", linie[6].trimmed().replace(",","."));
		defaultDatabase()->query("pozitiiIntrariObiecteInventar")->setValue("cantitate", linie[5].trimmed());
		defaultDatabase()->query("pozitiiIntrariObiecteInventar")->post();
		defaultDatabase()->query("pozitiiIntrariObiecteInventar")->close();
		defaultDatabase()->query("acteIntrariObiecteInventar")->close();
		defaultDatabase()->query("repereObiecteInventar")->close();
	}
*/
	QString dir=QFileDialog::getExistingDirectory(this,tr("Locatie OBINV"));
	if (m_ObinvDir.exists(dir))
		m_ObinvDir.cd(dir);
	m_obinvFound = checkForObinv();
	preiaButton->setEnabled(m_obinvFound);
}

quint64 PreluareObinvDosObiecteInventar::getUmId(const QString um) 
{
	if (!defaultDatabase()->query("um")->locate("denumire",um,Query::SortedSearch))
	{
		defaultDatabase()->query("um")->insert();
		defaultDatabase()->query("um")->setValue("denumire", um);
		defaultDatabase()->query("um")->post();
	}
	return defaultDatabase()->query("um")->value("id").toULongLong();
}


void PreluareObinvDosObiecteInventar::on_preiaButton_clicked()
{
	QList<quint64> gids;
	QFile fges(m_ObinvDir.absoluteFilePath("GEST.MAT"));
	if (!fges.open(QIODevice::ReadOnly))
	{
		QMessageBox::critical(this, tr("Preluare OBINV"), tr("Nu pot deschide fisierul cu gestiunile.\nPreluare nu mai poate continua."));
		return;
	}
	setDisabled(true);
	qApp->processEvents();
	while(!fges.atEnd())
	{
		if (sizeof(gestiune) != fges.read((char*)&gestiune, sizeof(gestiune)))
		{
			QMessageBox::critical(this, tr("Preluare OBINV"), tr("Date eronate in fisierul de gestiuni.\nPreluare nu mai poate continua."));
			setEnabled(true);
			return;
		}
		gestiune.denumire[30]=0;
		defaultDatabase()->query("gestiuniObiecteInventar")->insert();
		defaultDatabase()->query("gestiuniObiecteInventar")->setValue("denumire",QString(gestiune.denumire).trimmed().toLower());
		defaultDatabase()->query("gestiuniObiecteInventar")->setValue("cod",QString::number(gestiune.cod));
		defaultDatabase()->query("gestiuniObiecteInventar")->post();
		gids.push_back(defaultDatabase()->query("gestiuniObiecteInventar")->value("id").toULongLong());
	}

	QFile frep(m_ObinvDir.absoluteFilePath("MBAZA.MAT"));
	if (!frep.open(QIODevice::ReadOnly))
	{
		QMessageBox::critical(this, tr("Preluare OBINV"), tr("Nu pot deschide fisierul cu reperele.\nPreluare nu mai poate continua."));
		setEnabled(true);
		return;
	}
	progressBar->setMaximum(frep.size());
	while(!frep.atEnd())
	{
		if (sizeof(reper) != frep.read((char*)&reper, sizeof(reper)))
		{
			QMessageBox::critical(this, tr("Preluare OBINV"), tr("Date eronate in fisierul de repere.\nPreluare nu mai poate continua."));
			setEnabled(true);
			return;
		}

		if (!reper.activ || strncmp(reper.ident, "lpg", 3))
			continue;

		reper.nume[30]=0;
		reper.um[5]=0;
		reper.cpsa[13]=0;
		reper.nr_inv[10]=0;
		defaultDatabase()->query("repereObiecteInventar")->bindValue("id_gestiune",gids[reper.gestiune]);
		defaultDatabase()->query("repereObiecteInventar")->select();
		defaultDatabase()->query("repereObiecteInventar")->insert();
		defaultDatabase()->query("repereObiecteInventar")->setValue("denumire",QString(reper.nume).trimmed().toLower());
		defaultDatabase()->query("repereObiecteInventar")->setValue("id_um",getUmId(reper.um));
		defaultDatabase()->query("repereObiecteInventar")->setValue("cod_cpsa",QString(reper.cpsa).trimmed().toLower());
		defaultDatabase()->query("repereObiecteInventar")->setValue("nr_inv",QString(reper.nr_inv).trimmed().toLower());
		defaultDatabase()->query("repereObiecteInventar")->post();
		QList<Stoc> stocuri;
		for(int i=0;i<50;i++)
		{
			if (!reper.preturi[i].stoc || !reper.preturi[i].pu)
				continue;

			bool gasit=false;
			for(int j=0;j<stocuri.size();j++)
			{
				
				if (QDate(reper.preturi[i].aa, reper.preturi[i].ll, reper.preturi[i].zz) == stocuri[j].data && reper.preturi[i].pu==stocuri[j].pu)
				{
					gasit=true;
					stocuri[j].stoc+=reper.preturi[i].stoc;
				}
			}
			if (!gasit)
			{
				Stoc st;
				st.data=QDate(reper.preturi[i].aa, reper.preturi[i].ll, reper.preturi[i].zz);
				if (st.data.isNull())
					st.data=QDate(2008, 1, 1);
				st.pu=reper.preturi[i].pu;
				st.stoc=reper.preturi[i].stoc;
				stocuri.push_back(st);
			}
		}
		foreach(Stoc st, stocuri)
		{
			defaultDatabase()->query("acteIntrariObiecteInventar")->bindValue(":data", st.data);
			defaultDatabase()->query("acteIntrariObiecteInventar")->select();
			if (!defaultDatabase()->query("acteIntrariObiecteInventar")->locate("numar","sold", Query::SortedSearch))
			{
				defaultDatabase()->query("acteIntrariObiecteInventar")->insert();
				defaultDatabase()->query("acteIntrariObiecteInventar")->setValue("numar", "sold");
				defaultDatabase()->query("acteIntrariObiecteInventar")->setValue("data", st.data);
				defaultDatabase()->query("acteIntrariObiecteInventar")->post();
			}
			defaultDatabase()->query("pozitiiIntrariObiecteInventar")->bindValue("id_act", defaultDatabase()->query("acteIntrariObiecteInventar")->value("id"));
			defaultDatabase()->query("pozitiiIntrariObiecteInventar")->select();
			defaultDatabase()->query("pozitiiIntrariObiecteInventar")->insert();
			defaultDatabase()->query("pozitiiIntrariObiecteInventar")->setValue("data", st.data);
			defaultDatabase()->query("pozitiiIntrariObiecteInventar")->setValue("id_reper", defaultDatabase()->query("repereObiecteInventar")->value("id"));
			defaultDatabase()->query("pozitiiIntrariObiecteInventar")->setValue("pret", st.pu);
			defaultDatabase()->query("pozitiiIntrariObiecteInventar")->setValue("cantitate", st.stoc);
			defaultDatabase()->query("pozitiiIntrariObiecteInventar")->post();
		}
		defaultDatabase()->query("pozitiiIntrariObiecteInventar")->close();
		defaultDatabase()->query("acteIntrariObiecteInventar")->close();
		defaultDatabase()->query("repereObiecteInventar")->close();
		progressBar->setValue(frep.pos());
	}
	QMessageBox::information(this, tr("Preluare OBINV"), tr("Preluare a fost executata cu succes."));
	setEnabled(true);
	accept();
}

bool PreluareObinvDosObiecteInventar::checkForObinv()
{
	return QFile::exists(m_ObinvDir.absoluteFilePath("GEST.MAT"));
}

PreluareObinvDosObiecteInventar::~PreluareObinvDosObiecteInventar()
{
}
